package com.csl.jsonpreference.ui

import android.content.DialogInterface
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.csl.jsonpreference.R
import com.csl.jsonpreference.configdes.JsonArrayPreference
import com.csl.jsonpreference.configdes.JsonObjectPreference
import com.csl.jsonpreference.databinding.DialogJsonpreferenceBinding
import com.csl.jsonpreference.util.CLog
import com.csl.ui.base.CenterDialog
import com.csl.ui.base.TipDialog


class JsonPreferenceDialog : CenterDialog() {
    companion object {
        private val TAG = "jsonDialog"
    }

    lateinit var binding: DialogJsonpreferenceBinding


    var rootFragment: JsonPreferenceFragment = JsonPreferenceFragment()
    var showFragment: Fragment? = null
    var fragmentListener = object : OnOpenOrCloseListener {
        override fun onGroupOpen(group: JsonObjectPreference) {
            var fragment = JsonPreferenceFragment()
            fragment.onOpenOrCloseListener = this
            fragment.configData = group
            showFragment(fragment, "${group.title}")
        }

        override fun onArrayOpen(array: JsonArrayPreference) {
            var fragment = JsonArrayFragment()
            fragment.onOpenOrCloseListener = this
            fragment.configData = array
            showFragment(fragment, "${array.title}")
        }

        override fun onClose() {
        }

    }

    var titleText: String = ""
    var onConfigEnd: ((String) -> Unit)? = null


    override fun onDestroy() {
        super.onDestroy()
    }

    fun showToast(str: String) {
        requireActivity().runOnUiThread {
            Toast.makeText(requireContext(), "$str", Toast.LENGTH_SHORT).show()
        }
    }

    fun showFragment(fragment: Fragment, title: String) {
        binding?.jsonTvTitle?.text = title
        if (fragment == rootFragment) {
            binding?.ivBack?.visibility = View.VISIBLE
            binding?.ivBack?.setImageResource(R.drawable.ic_close)
        } else {
            binding?.ivBack?.visibility = View.VISIBLE
            binding?.ivBack?.setImageResource(R.drawable.ic_back)
        }
        showFragment = fragment
        try {
            childFragmentManager.beginTransaction()
                .add(R.id.fl_container, fragment, title)
                .addToBackStack(title)
                .commit()
        } catch (e: Exception) {
        }
    }


    //
//
    override fun onCancel(dialog: DialogInterface) {
//        childFragmentManager.back
        if (rootFragment.isResumed) {
//            super.onBackPressed()
            super.onCancel(dialog)
        } else {
            needBack()
//            showFragment(rootFragment, rootFragment.configData!!.title)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        getDialog()?.requestWindowFeature(Window.FEATURE_NO_TITLE); // 不显示标题栏
        binding = DialogJsonpreferenceBinding.inflate(inflater)

        initView()
        initListener()
        return binding!!.root
    }

    override fun onStart() {
        super.onStart()
        initData()

    }

    fun initView() {
        rootFragment.onOpenOrCloseListener = fragmentListener
        dialog?.setOnKeyListener { dialogInterface, i, keyEvent ->
            CLog.d(TAG, "点击: $i  $keyEvent")
            if (i == KeyEvent.KEYCODE_BACK && keyEvent.action == MotionEvent.ACTION_UP) {
                needBack()
                true
            } else {
                false
            }
        }
    }

    //
    fun needBack() {

//        if(showFragment!= null && showFragment != rootFragment) {
//            childFragmentManager.beginTransaction().remove(showFragment!!).commit()
//            for(i in childFragmentManager.fragments.asReversed()) {
//                if(i!= null && i.isVisible) {
//                    CLog.d("fragment", "搜索到fragment:" + i)
//                    showFragment = i
//                    break
//                }
//            }
//        } else {
//            var dialog = TipDialog("是否取消修改?", "", "继续修改", "取消修改") {
//                if (!it) {
//                    dismiss()
//                }
//                true
//            }
//            dialog.show(requireActivity().supportFragmentManager, "exitdialog")
//        }

        CLog.d("jsonback", "返回键判断")

//        childFragmentManager.stack

        when (childFragmentManager.backStackEntryCount) {
            0, 1 -> {
                var dialog = TipDialog("取消修改并退出?", "", "继续修改", "退出") {
                    if (!it) {
                        dismiss()
                    }
                    true
                }
                dialog.show(requireActivity().supportFragmentManager, "exitdialog")
            }

            2 -> {
                binding?.ivBack?.visibility = View.VISIBLE
                binding?.ivBack?.setImageResource(R.drawable.ic_close)
                childFragmentManager.popBackStack()
            }
            else -> {
                binding?.ivBack?.visibility = View.VISIBLE
                binding?.ivBack?.setImageResource(R.drawable.ic_back)
                childFragmentManager.popBackStack()
            }
        }

//        if (!rootFragment.isResumed) {
//            if (childFragmentManager.backStackEntryCount <= 1) {
//                binding?.ivBack?.visibility = View.VISIBLE
//                binding?.ivBack?.setImageResource(R.drawable.ic_close)
//            } else {
//                binding?.ivBack?.visibility = View.INVISIBLE
//                binding?.ivBack?.setImageResource(R.drawable.ic_back)
//            }
//            childFragmentManager.popBackStack()
//
////            showFragment(rootFragment, rootFragment.configData!!.title)
//        } else {
//            var dialog = TipDialog("是否取消修改?", "", "继续修改", "取消修改") {
//                if (!it) {
//                    dismiss()
//                }
//                true
//            }
//            dialog.show(requireActivity().supportFragmentManager, "exitdialog")
//        }
    }

    private fun initListener() {
        binding?.ivBack?.setOnClickListener {
            needBack()
        }
        binding?.ivCommit?.setOnClickListener {
            if (!rootFragment.isResumed) {
                showFragment(rootFragment, rootFragment.configData!!.title)
            } else {
                rootFragment.configData?.let {
                    dismiss()
                    onConfigEnd?.let { call ->
                        call(it.jsonData.toString())
                    }
                }
            }
        }
    }

    private fun initData() {
        showFragment(rootFragment, rootFragment.configData!!.title)
    }


}